<?php
/**
 * 咨询师
 *
 * User: kaikaic
 * Date: 2018/10/30
 * Time: 18:36
 */

namespace app\psy\controller;

use app\admin\service\CityService;
use app\admin\service\TagsService;
use app\psy\service\ConsultantExtendService;
use app\psy\service\ConsultantIndexService;
use app\psy\service\ConsultantService;
use controller\BasicAdmin;
use service\ConfigService;
use service\DateService;
use think\Db;

class Consultant extends BasicAdmin {

    protected $table = "PsyConsultant";

    public function index() {
        $this->title = "咨询师";

        $query = array();
        $query['name'] = $this->request->get("name");

        $db = Db::name($this->table);
        if ($query['name']) {
            $db->whereLike("name", "%{$query['name']}%");
        }

        return parent::listRecord($db);
    }

    /**
     * 咨询师-添加
     */
    public function add() {
        if ($this->request->isGet()) {
            $vo = array();

            return view('form', [
                'title'=>'新增咨询师',
                'vo'=>$vo,
                'image'=>ConfigService::defaultImage(),
                'psy_consult'=>$this->readCategoryConfig("psy_consult"),
                'tag_list'=>TagsService::getInstance()->listTagsByCategory("psy_qualification"),
                'tags_time'=>TagsService::getInstance()->getTagsArrayByAbbr("tags_time"),
                'tag_type_list'=>TagsService::getInstance()->getTagsArrayByAbbr("tags_type"),
                'factions_list'=>TagsService::getInstance()->getTagsArrayByAbbr("tags_factions"),
                'area_list'=>json_encode(CityService::getInstance()->listCityArray())
            ]);
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->doInsertAction($data)) {
                $this->showSuccess('新增成功！', '/psy/consultant/index');
            }else {
                $this->error('新增失败，请稍候再试！');
            }
        }
    }

    /**
     * 咨询师-编辑
     */
    public function edit() {
        if ($this->request->isGet()) {
            $id = $this->request->get('id', '');
            if (empty($id)) {
                $this->error('参数错误，请稍候再试！');
            }

            $record = ConsultantService::getInstance()->find($id);
            if (empty($record)) {
                $this->error('记录不存在，请重新操作!');
            }

            $record['type_ids'] = unserialize($record['type_ids']);

            if (!$record['goodat_ids']) {
                $record['goodat_ids'] = array();
            }else {
                $record['goodat_ids'] = unserialize($record['goodat_ids']);
            }

            if (!$record['factions_ids']) {
                $record['factions_ids'] = array();
            }else {
                $record['factions_ids'] = unserialize($record['factions_ids']);
            }
            if (!$record['period_ids']) {
                $record['period_ids'] = array();
            }else {
                $record['period_ids'] = unserialize($record['period_ids']);
            }
            return view('form', [
                'title'=>'编辑咨询师',
                'vo'=>$record,
                'image'=>ConfigService::defaultImage(),
                'psy_consult'=>$this->readCategoryConfig("psy_consult"),
                'tag_list'=>TagsService::getInstance()->listTagsByCategory("psy_qualification"),
                'tags_time'=>TagsService::getInstance()->getTagsArrayByAbbr("tags_time"),
                'tag_type_list'=>TagsService::getInstance()->getTagsArrayByAbbr("tags_type"),
                'factions_list'=>TagsService::getInstance()->getTagsArrayByAbbr("tags_factions"),
                'area_list'=>json_encode(CityService::getInstance()->listCityArray())
            ]);
        }

        if ($this->request->isPost()) {
            $id = $this->request->post('id', '');
            if (empty($id)) {
                $this->error('参数错误，请稍候再试！');
            }

            $data = $this->request->post();
            if ($this->doInsertAction($data)) {
                $this->showSuccess('编辑成功！', '/psy/consultant/index');
            }else {
                $this->error('编辑失败，请稍候再试！');
            }
        }
    }

    /**
     * 咨询师-删除
     */
    public function remove() {
        $id = intval($this->request->post('id', ''));
        if (empty($id)) {
            $this->error('参数错误!');
        }

        $record = ConsultantService::getInstance()->find($id);
        if (empty($record)) {
            $this->error('记录不存在，请重新操作!');
        }

        $result = ConsultantService::getInstance()->remove(array('id'=>$id));
        if ($result) {
            $this->success('删除成功!', '');
        }else {
            $this->error('删除失败，请重新再试!');
        }
    }

    /**
     * 咨询师-审核
     */
    public function auditing() {
        $id = intval($this->request->param('id', ''));
        if (empty($id)) {
            $this->error('参数错误!');
        }

        $record = ConsultantService::getInstance()->find($id);
        if (empty($record)) {
            $this->error('记录不存在，请重新操作!');
        }

        if ($this->request->isGet()) {
            return view('audit', ['title'=>'咨询师审核', 'vo'=>$record]);
        }

        if ($this->request->isPost()) {
            $audit = intval($this->request->post("audit"));
            $status = 3;
            if ($audit == 1) {
                $status = 2;
            }

            $params = array();
            $params['status'] = $status;
            $result = ConsultantService::getInstance()->update($params, $id);
            if ($result) {
                $this->success('操作成功!', '');
            }else {
                $this->error('操作失败，请重新再试!');
            }
        }
    }

    /**
     * 咨询师-屏蔽
     */
    public function forbidden() {
        $id = intval($this->request->param('id', ''));
        if (empty($id)) {
            $this->error('参数错误!');
        }

        $record = ConsultantService::getInstance()->find($id);
        if (empty($record)) {
            $this->error('记录不存在，请重新操作!');
        }

        $params = array();
        $params['status'] = 4;
        $result = ConsultantService::getInstance()->update($params, $id);
        if ($result) {
            $this->success('操作成功!', '');
        }else {
            $this->error('操作失败，请重新再试!');
        }
    }

    /**
     * 咨询师-解禁
     */
    public function open() {
        $id = intval($this->request->param('id', ''));
        if (empty($id)) {
            $this->error('参数错误!');
        }

        $record = ConsultantService::getInstance()->find($id);
        if (empty($record)) {
            $this->error('记录不存在，请重新操作!');
        }

        $params = array();
        $params['status'] = 2;
        $result = ConsultantService::getInstance()->update($params, $id);
        if ($result) {
            $this->success('操作成功!', '');
        }else {
            $this->error('操作失败，请重新再试!');
        }
    }

    /**
     * 数据写入
     */
    protected function doInsertAction($data) {
        if(isset($data['type_ids'])){
            $data['type_ids'] = serialize($data['type_ids']);
        }else{
            $data['type_ids'] = serialize(array());
        }


        if(isset($data['factions_ids'])){
            $data['factions_ids'] = serialize($data['factions_ids']);
        }else{
            $data['factions_ids'] = serialize(array());
        }

        if(isset($data['goodat_ids'])){
            $data['goodat_ids'] = serialize($data['goodat_ids']);
        }else{
            $data['goodat_ids'] = serialize(array());
        }

        if(isset($data['period_ids'])){
            $data['period_ids'] = serialize($data['period_ids']);
        }else{
            $data['period_ids'] = serialize(array());
        }
//        $data['factions_ids'] = serialize($data['factions_ids']);
//        $data['goodat_ids'] = serialize($data['goodat_ids']);
//        $data['period_ids'] = serialize($data['period_ids']);

        if (empty($data['id'])) {
            $data['sort'] = ConsultantService::getInstance()->getMaxSort() + 1;
            $data['status'] = 1;
            $data['create_time'] = time();

            $result = ConsultantService::getInstance()->insert($data);
            if ($result) {
                ConsultantIndexService::getInstance()->updateTypeIndex($data);
                ConsultantIndexService::getInstance()->updateFactionsIndex($data);
            }
        } else {
            $id = intval($data['id']);

            $result = ConsultantService::getInstance()->update($data, $id);
            if ($result) {
                ConsultantIndexService::getInstance()->updateTypeIndex($data);
                ConsultantIndexService::getInstance()->updateFactionsIndex($data);
            }
        }

        return $result;
    }

    /**
     * 推荐到首页
     */
    public function recommend() {
        $id = intval($this->request->param('id', ''));
        if (empty($id)) {
            $this->error('参数错误!');
        }

        $record = ConsultantService::getInstance()->find($id);
        if (empty($record)) {
            $this->error('记录不存在，请重新操作!');
        }

        $recommend = 0;
        $rec = intval($this->request->param("rec"));
        if ($rec == 1) {
            $recommend = 1;
        }

        if ($record['recommend'] == $recommend) {
            $this->success('操作完成!', '');
        }

        $params = array();
        $params['recommend'] = $recommend;
        $result = ConsultantService::getInstance()->update($params, $id);
        if ($result) {
            $this->success('操作成功!', '');
        }else {
            $this->error('操作失败，请重新再试!');
        }
    }

    /**
     * 咨询时段示例
     */
    public function hour() {


        // 生成记录
        //$rs = ConsultantExtendService::getInstance()->insert($params, 3);
       


        $time = time();

        $week = $this->getWeekday($time);
        $first = $week[0];

        $weekDate = array();
        for ($i=0; $i<7; $i++) {
            $weekDate[] = date("Y-m-d", strtotime("+{$i} day", strtotime($first)));
        }

        // 上午：9点，10点，11点
        $morning = array(9, 10, 11);
        $morningDate = array();
        foreach ($morning as $value) {

            $dateArray = array();
            foreach ($weekDate as $date) {
                $dateArray[] = array($value, strtotime($date) + $value * 3600);
            }

            $morningDate[] = $dateArray;
        }

        // 下午 14点，15点，16点，17点
        $afternoon = array(14, 15, 16, 17);
        $afternoonDate = array();
        foreach ($afternoon as $value) {

            $dateArray = array();
            foreach ($weekDate as $date) {
                $dateArray[] = array($value, strtotime($date) + $value * 3600);
            }

            $afternoonDate[] = $dateArray;
        }

        // 晚上 19点，20点，21点
        $night = array(19, 20, 21);
        $nightDate = array();
        foreach ($night as $value) {

            $dateArray = array();
            foreach ($weekDate as $date) {
                $dateArray[] = array($value, strtotime($date) + $value * 3600);
            }

            $nightDate[] = $dateArray;
        }

        return view('hour', [
            'title'=>'咨询时段',
            "today"=>date("Y-m-d"),
            'week_date'=>$weekDate,
            'morning'=>$morningDate,
            'afternoon'=>$afternoonDate,
            'night'=>$nightDate
        ]);
    }

    private function getWeekday($time) {
        $time = empty($time) ? time() : $time;

        $w = date('w', $time);
        $w = $w ?  $w : 7;

        $month = date('m', $time);
        $day = date('d', $time);
        $year = date('Y', $time);

        $data[] = date('Y-m-d', mktime(0, 0, 0, $month, $day - $w + 1, $year));
        $data[] = date('Y-m-d', mktime(0, 0, 0, $month, $day + 7 - $w, $year));

        return $data;
    }

    /**
     * 列表数据处理
     */
    protected function _index_data_filter(&$data) {
        $size = count($data);
        $config = ConfigService::consultantStatus();
        $cityList = CityService::getInstance()->listCities();
        $consultType = $this->readCategoryConfig("psy_consult");
//        $tagsList = TagsService::getInstance()->getTagsArrayByAbbr("psy_qualification");

        for ($i=0; $i<$size; $i++) {
            $tmp = $data[$i];
            $tmp['type_txt'] = '';
            $typeStr = "";
            if($tmp['type_ids']){
                $type = unserialize($tmp['type_ids']);
                foreach ($type as $key) {
                    $typeStr .= $consultType[$key] . ",";
                }
                $tmp['type_txt'] = trim($typeStr, ",");
            }

//            $qualification = "";
//            if($tmp['qualification']){
//                if (isset($tagsList[$tmp['qualification']])) {
//                    $qualification = $tagsList[$tmp['qualification']];
//                }
//            }

//            $tmp['qualification'] = $qualification;
            $tmp['status_txt'] = $config[$tmp['status']];
            if($tmp['city_id']){
                $tmp['city_txt'] = $cityList[$tmp['city_id']];
            }
            $tmp['city_txt'] = '';

            $data[$i] = $tmp;
        }
    }
    public function SignInfo(){
        $id = intval($this->request->param('id', ''));
        $record = ConsultantService::getInstance()->single(array('id'=>$id));
        // 咨询师培训
        $dataArray['train'] = $this->consultantTrain($id);
        // 咨询师教育经历
        $dataArray['education'] = $this->consultantEducation($id);

        $dataArray['Pexp'] = $this->consultantPexp($id);
        $dataArray['Supexp'] = $this->consultantSupexp($id);
        $dataArray['basic'] = $this->consultantBasic($record);

        return view('signinfo', [
            'title'=>'咨询师详情',
            'vo'=>$dataArray,
        ]);
    }
    private function consultantTrain($id) {
        $where = array();
        $where['consultant_id'] = $id;
        $records = ConsultantExtendService::getInstance()->select($where, 1);

        $trains = array();
        for ($i=0; $i<count($records); $i++) {
            $temp = array();

            $s = date("Y-m", strtotime($records[$i]['start_date']));
            $e = date("Y-m", strtotime($records[$i]['end_date']));
            $temp['date'] = $s . "至" . $e;
            $temp['start_date'] = $records[$i]['start_date'];
            $temp['end_date'] = $records[$i]['end_date'];
            $temp['intro'] = $records[$i]['intro'];
            $temp['hours'] = $records[$i]['hours'];
            $temp['theme'] = $records[$i]['theme'];
            $temp['leader'] = $records[$i]['leader'];
            $temp['id'] = $records[$i]['id'];
            $temp['photos'] = explode(',',$records[$i]['photos']);
            $trains[] = $temp;
        }

        return $trains;
    }
    private function consultantBasic($basic) {
        $city = CityService::getInstance()->single(array('area_id'=>$basic['city_id']));
        $basic['city'] = $city['area_name'];
        // 资质
        $tagsList = TagsService::getInstance()->getTagsArrayByAbbr("psy_qualification");
        if ($basic['qualification']) {
            $basic['qualification'] = $tagsList[$basic['qualification']];
        }else {
            $basic['qualification'] = "";
        }
        $basic['qualification'] = $basic['qualificationtext'];
        $consultType = $this->readCategoryConfig("psy_consult");
        $type = unserialize($basic['type_ids']);
        $typeArr = array();
        $typeStr = "";
        $i = 0;
        foreach ($type as $key) {
            $typeStr .= $consultType[$key] . "/";
            $typeArr[$i]['id'] = $key;

            $typeArr[$i]['name'] = $consultType[$key];
            $i++;
        }
        $basic['type_txt'] = trim($typeStr, "/");
        $basic['type'] = $typeArr;
        $factionsType = TagsService::getInstance()->getTagsArrayByAbbr("tags_factions");

        $factionids = unserialize($basic['factions_ids']);
        $typeStr = "";
        foreach ($factionids as $key) {
            $typeStr[$key] = $factionsType[$key];
        }
        $basic['factionsType'] = $typeStr;

        $tags_type = TagsService::getInstance()->getTagsArrayByAbbr("tags_type");

        $goodat_ids = unserialize($basic['goodat_ids']);
        $goodatStr = "";
        foreach ($goodat_ids as $key) {
            $goodatStr[$key] = $tags_type[$key];
        }
        $basic['goodatType'] = $goodatStr;
        $basic['peroidType'] = unserialize($basic['period_ids']);
        return $basic;
    }
    private function consultantEducation($id) {
        $where = array();
        $where['consultant_id'] = $id;
        $records = ConsultantExtendService::getInstance()->select($where);

        $educations = array();
        for ($i=0; $i<count($records); $i++) {
            $temp = array();

            $s = date("Y-m", strtotime($records[$i]['start_date']));
            $e = date("Y-m", strtotime($records[$i]['end_date']));
            $temp['date'] = $s . "至" . $e;
            $temp['start_date'] = $records[$i]['start_date'];
            $temp['end_date'] = $records[$i]['end_date'];
            $temp['school'] = $records[$i]['school'];
            $temp['major'] = $records[$i]['major'];
            $temp['education'] = $records[$i]['education'];
            $temp['id'] = $records[$i]['id'];
            $temp['photos'] = explode(',',$records[$i]['photos']);
            $educations[] = $temp;
        }

        return $educations;
    }
    private function consultantPexp($id) {
        $where = array();
        $where['consultant_id'] = $id;
        $records = ConsultantExtendService::getInstance()->select($where, 5);
        $pexps = array();
        for ($i=0; $i<count($records); $i++) {
            $temp = array();
            $s = date("Y-m", strtotime($records[$i]['start_date']));
            $e = date("Y-m", strtotime($records[$i]['end_date']));
            $temp['date'] = $s . "至" . $e;
            $temp['start_date'] = $records[$i]['start_date'];
            $temp['end_date'] = $records[$i]['end_date'];
            $temp['intro'] = $records[$i]['intro'];
            $temp['hours'] = $records[$i]['hours'];
            $temp['leading'] = $records[$i]['leading'];
            $temp['leadphone'] = $records[$i]['leadphone'];
            $temp['leadname'] = $records[$i]['leadname'];
            $temp['id'] = $records[$i]['id'];
            $temp['photos'] = explode(',',$records[$i]['photos']);
            $pexps[] = $temp;
        }
        return $pexps;
    }
    private function consultantSupexp($id) {
        $where = array();
        $where['consultant_id'] = $id;
        $records = ConsultantExtendService::getInstance()->select($where, 6);

        $supexps = array();
        for ($i=0; $i<count($records); $i++) {
            $temp = array();

            $s = date("Y-m", strtotime($records[$i]['start_date']));
            $e = date("Y-m", strtotime($records[$i]['end_date']));
            $temp['date'] = $s . "至" . $e;
            $temp['start_date'] = $records[$i]['start_date'];
            $temp['end_date'] = $records[$i]['end_date'];
            $temp['intro'] = $records[$i]['intro'];
            $temp['hours'] = $records[$i]['hours'];
            $temp['supname'] = $records[$i]['supname'];
            $temp['forwards'] = $records[$i]['forwards'];
            $temp['id'] = $records[$i]['id'];
            $temp['photos'] = explode(',',$records[$i]['photos']);
            $supexps[] = $temp;
        }

        return $supexps;
    }
}

